<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<span>
				<el-input v-model="queryParams.licenseName" class="zs-select-md zs-space-right-sm" placeholder="证件名称" clearable @blur="queryList" />
				<el-input v-model="queryParams.licenseCode" class="zs-select-md zs-space-right-sm" placeholder="证件编号" clearable @blur="queryList" />
				<el-select v-model="queryParams.licenseType" class="zs-select-md zs-space-right-sm" placeholder="证照类型" clearable @change="queryList">
					<el-option v-for="item in dictObj.PROPERTY_CERTIFICATE_TYPE" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
				</el-select>
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': queryParams.processNam || queryParams.status }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-select v-model="queryParams.validityTypeList" collapse-tags collapse-tags-tooltip multiple class="zs-select-md zs-space-right-sm" placeholder="有效天数" clearable @change="queryList" :teleported="false">
							<el-option v-for="item in dictObj.PROJECT_LICENSE_VALIDITY_TYPE" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
						<el-select v-model="queryParams.status" class="zs-select-md zs-space-right-sm" placeholder="生效状态" @change="queryList" :teleported="false">
							<el-option v-for="item in dictObj.VALIDATE_FLAG" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList" v-btnPermi="{ permis: ['p_btn_property_project_license_list_query'] }"> 查询 </el-button>
			</span>
			<span>
				<el-button class="zs-btn-plain zs-btn-md" v-btnPermi="{ permis: ['p_btn_property_project_license_list_export'], businessFlag: true }" @click="handleDownload(queryParams, licenseExportApi, projectName + '证照')">
					<el-icon class="el-icon--left"> <Upload /> </el-icon>导出
				</el-button>
				<el-button class="zs-btn-plain zs-btn-md" v-btnPermi="{ permis: ['p_btn_property_project_license_list_import'], businessFlag: true }" @click="handleOpenImportDrawer()">
					<el-icon class="el-icon--left"> <Download /> </el-icon>导入
				</el-button>
				<el-button class="zs-btn-md zs-btn-primary" @click="openDrawer(false, 'add', {}, 'base')" v-btnPermi="{ permis: ['p_btn_property_project_license_list_add'], businessFlag: true }">新增</el-button>
			</span>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column type="index" label="序号" width="60" align="center" :index="index => index + 1 + (tableData.currentPage - 1) * curPageSize" />
				<el-table-column prop="licenseName" label="证照名称" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="licenseCode" label="证照编号" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="licenseTypeName" label="证照类型" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="licenseIssuingAuthority" label="发证机关" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="formatValidityIssueTime" label="签发日期" width="110" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column label="有效期至" show-overflow-tooltip width="110" align="left">
					<template #default="{ row }">
						<span>{{ row.validityStatus == 1 ? '永久' : row.formatValidityTime }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="formatValidityTimeValue" width="120" label="剩余有效时间" show-overflow-tooltip :formatter="defaultTableData" align="left" />
				<el-table-column width="120" label="证照失效通知人" show-overflow-tooltip align="left">
					<template #default="{ row }">
						<span v-if="row.validityRealName">{{ row.validityRealName }}</span>
						<span v-else-if="row.validityWarnStatus && !row.validityRealName" class="zs-text-red">未配置人员</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column prop="effectiveState" label="是否年审" align="center">
					<template #default="{ row }">
						<span>{{ row.annualAuditStatus == 1 ? '是' : '否' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="formatAnnualAuditTime" label="下次年审" width="110" align="left" :formatter="defaultTableData" />
				<el-table-column width="120" label="年审通知人" show-overflow-tooltip align="left">
					<template #default="{ row }">
						<span v-if="row.annualRealName">{{ row.annualRealName }}</span>
						<span v-else-if="row.annualWarnStatus && !row.annualRealName" class="zs-text-red">未配置人员</span>
						<span v-else>-</span>
					</template>
				</el-table-column>
				<el-table-column prop="effectiveState" label="生效状态" align="center">
					<template #default="{ row }">
						<span :class="row.status == 1 ? 'zs-validata-status-yes' : 'zs-validata-status-no'">{{ row.status == 1 ? '有效' : '失效' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="审核状态" align="center">
					<template #default="scope">
						<div :class="{ 'zs-approval-status-yes': scope.row.auditStatus == 1, 'zs-approval-status-no': scope.row.auditStatus == 0, 'zs-approval-status-wait': scope.row.auditStatus == null || scope.row.auditStatus == '' }">
							{{ getDictoryTxt('AUDIT_STATUS', scope.row.auditStatus) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="" label="定义" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="openDrawer(true, 'info', row, 'base')" v-btnPermi="{ permis: ['p_btn_property_project_license_list_view'] }">查看</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="openDrawer(false, 'edit', row, 'base')" v-btnPermi="{ permis: ['p_btn_property_project_license_list_edit'], businessFlag: true }">编辑</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="" label="操作" width="120" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" link size="small" @click="openDrawer(false, 'edit', row, 'setting')" v-btnPermi="{ permis: ['p_btn_property_project_license_list_config'], businessFlag: true }">配置</el-button>
						<el-divider direction="vertical" />
						<el-button class="zs-link" link size="small" @click="downLoad(row.id)" v-btnPermi="{ permis: ['p_btn_property_project_license_list_download'], businessFlag: true }">下载</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
		</div>
	</div>

	<!-- 定义抽屉 -->
	<DrawerLicense :isShow="drawer.base.isShowDrawer" :isReadOnly="drawer.base.isReadOnly" :handleType="drawer.base.handleType" :currentRow="currentRow.data" @close="closeDrawer($event, 'base')"> </DrawerLicense>

	<!-- 配置 -->
	<DrawerSetting :isShow="drawer.setting.isShowDrawer" :isReadOnly="drawer.setting.isReadOnly" :handleType="drawer.setting.handleType" :currentRow="currentRow.data" @close="closeDrawer($event, 'setting')"> </DrawerSetting>

	<!-- 导入 -->
	<hsImportData v-if="importDrawer.isShow" :isShow="importDrawer.isShow" @clickImportBtn="importFile($event, licenseImportApi, route.query.projectCode, queryList)" @close="closeImportDrawer" @download="handleDownload({}, licenseExportApi, projectName + '证照')" />
</template>

<script setup>
	import DrawerLicense from './components/drawerLicense.vue';
	import DrawerSetting from './components/drawerSetting.vue';
	import { licenseListApi, licenseFileApi, licenseExportApi, licenseImportApi } from '@/api/license.js';
	import { ElMessageBox } from 'element-plus';
	import { ref, reactive } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';
	import { defaultTableData, parseTime, downloadNewFile, deepClone, getDictoryTxt } from '@/utils/publicUtils';
	import useImportExport from '@/hooks/useImportExport';

	const { importDrawer, handleOpenImportDrawer, importFile, handleDownload, closeImportDrawer } = useImportExport();
	const route = useRoute();
	let store = useStore();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);
	const projectName = ref(decodeURI(route.query.projectName));

	let dictObj = store.getters.getDictObj(['VALIDATE_FLAG', 'PROPERTY_CERTIFICATE_TYPE', 'PROJECT_LICENSE_VALIDITY_TYPE']);

	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	//查询条件
	let queryParams = reactive({ projectCode: route.query.projectCode, pageNumber: 1, pageSize: curPageSize.value, status: '1' });

	// 抽屉相关
	let currentRow = reactive({ data: {} });
	let drawer = reactive({
		base: {
			handleType: '',
			isReadOnly: false,
			isShowDrawer: false,
		},
		setting: {
			handleType: '',
			isReadOnly: false,
			isShowDrawer: false,
		},
	});

	const openDrawer = (flag, handleType, row, drawerType) => {
		drawer[drawerType].isReadOnly = flag;
		drawer[drawerType].isShowDrawer = true;
		drawer[drawerType].handleType = handleType;
		currentRow.data = row;
	};

	const closeDrawer = (data, drawerType) => {
		drawer[drawerType].isShowDrawer = data.isShow;
		data.isRefresh && queryList('init');
	};

	// 列表数据源
	const queryList = async init => {
		if (process.env.NODE_ENV !== 'development') {
			let portalResourceList = JSON.parse(localStorage.getItem('portalResourceList'));
			if (init != 'init' && !portalResourceList.includes('p_btn_property_project_license_list_query')) return;
		}
		tableData.loading = true;
		let res = await licenseListApi(queryParams);
		if (res.data.code !== 200) return;
		initData(res.data.data.list);
		tableData.data = res.data.data.list || [];
		tableData.total = res.data.data.total || 0;
		tableData.loading = false;
	};

	const initData = list => {
		list.forEach(item => {
			item.formatValidityIssueTime = parseTime(item.validityIssueTime, '{y}-{m}-{d}');
			item.formatValidityTime = parseTime(item.validityTime, '{y}-{m}-{d}') || '-';
			item.formatAnnualAuditTime = parseTime(item.annualAuditTime, '{y}-{m}-{d}') || '-';
			item.formatValidityTimeValue = !isNaN(item.validityTimeValue) && item.validityTimeValue !== null ? item.validityTimeValue + '天' : item.validityTimeValue;
		});
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			queryParams.pageSize = size;
		} else {
			queryParams.pageNumber = size;
		}
		queryList('init');
	};

	//下载
	const downLoad = async id => {
		let res = await licenseFileApi({ id });
		if (res.data.code != 200) return;
		res.data.data.forEach(item => {
			const iframe = document.createElement('iframe');
			iframe.style.display = 'none'; // 防止影响页面
			iframe.style.height = 0; // 防止影响页面
			iframe.src = item.absolutePath;
			document.body.appendChild(iframe);
			setTimeout(() => {
				iframe.remove();
			}, 5 * 60 * 1000);
		});
	};

	queryList('init');
</script>
